package com.ysalliance.getFan.organization.network;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.just.agentweb.AgentWebConfig;
import com.ysalliance.getFan.organization.Bean.UserBean;
import com.ysalliance.getFan.organization.LucasUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import androidx.annotation.RequiresApi;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LogInterceptor implements Interceptor {

    private static final String TAG = LogInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Charset UTF8 = Charset.forName("UTF-8");

        // 打印请求报文
        Request request = chain.request();


        Request.Builder newBuilder = request
                .newBuilder();

        try {

            if (LucasUtil.isLogin()) {
//              //原来的token
//            newBuilder.addHeader("Authorization" , "Bearer "+ (   LucasUtil.getUser(Utils.getApp())==null?"false":LucasUtil.getUser(Utils.getApp()).getToken()   ));
                UserBean user = LitePal.findFirst(UserBean.class);


                String timestamp_str = (TimeUtils.getNowMills() + "").substring(0, 10);
                newBuilder.addHeader("sign",  EncryptUtils.encryptSHA1ToString(user.getUser_id() + '|' + user.getFirst_name() + '*' + "institution" + '%' + timestamp_str).toLowerCase()+"a");
                newBuilder.addHeader("version", AppUtils.getAppVersionName());
                newBuilder.addHeader("mobile", user.getUser_id());
                newBuilder.addHeader("timestamp", timestamp_str);
                newBuilder.addHeader("Accept", "application/json");
                newBuilder.addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android + " + DeviceUtils.getSDKVersionName() + "; zh-cn; +" + DeviceUtils.getModel() + ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");

                newBuilder.addHeader("devices", DeviceUtils.getUniqueDeviceId());

            } else {
                newBuilder.addHeader("version", AppUtils.getAppVersionName());
                newBuilder.addHeader("Accept", "application/json");
                newBuilder.addHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android + " + DeviceUtils.getSDKVersionName() + "; zh-cn; +" + DeviceUtils.getModel() + ") AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");

                newBuilder.addHeader("devices", DeviceUtils.getUniqueDeviceId());
            }


        } catch (Exception e) {
//            LucasUtil.upBugly("构造头的时候的代码段：" + e.getMessage().trim());
            LogUtils.e("构造头的时候的代码段： + e.getMessage().trim()");
        }

        request = newBuilder.build();


        RequestBody requestBody = request.body();
        String reqBody = null;
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            reqBody = buffer.readString(charset);
        }
        LogUtils.d(TAG, String.format("发送请求\nmethod：%s\nurl：%s\nheaders: %s\nbody：%s",
                request.method(), request.url(), request.headers(), reqBody));

        // 打印返回报文
        // 先执行请求，才能够获取报文
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        String respBody = null;
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }
            respBody = buffer.clone().readString(charset);
        }

        //cookie
        if (!response.headers("Set-Cookie").isEmpty()) {

            //解析Cookie
            for (String header : response.headers("Set-Cookie")) {
                if (header.contains("sessionid")) {
                    LogUtils.e("cookie信息", header.substring(header.indexOf("sessionid="), header.indexOf(";")));













//                    LucasUtil.pref_put(Utils.getApp(), "cookie", header.substring(header.indexOf("sessionid="), header.indexOf(";")));

















                }
            }
        }


        LogUtils.d(TAG, String.format("收到响应\n%s %s\n请求url：%s\n请求body：%s\n响应body：%s\n头部信息：%s",
                response.code(), response.message(), response.request().url(), reqBody, respBody, response.headers()));


        //全局重复登录拦截器
        try {
            JSONObject jsonObject = new JSONObject(respBody.toString().trim());
            if (jsonObject.optString("status", "").equals("401") || jsonObject.optString("status", "").equals("403")) {


            } else if (respBody.toString().trim().contains("Unable to resolve host")) {
                ToastUtils.showLong("网络解析错误，请切换Wifi或数据网络，检查后重试....");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return response;
    }

}




